// pages/habit_content/habit_content.js
const app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
       
        habit:{id:1,icon:'../../icon/water.png',name:'醒来喝水'},
        habit_times:[
            {value:'起床', selected: false},
            {value:'晨间', selected: false},
            {value:'中午', selected: false},
            {value:'午间', selected: false},
            {value:'晚间', selected: false},
            {value:'睡前', selected: false},
            {value:'全天', selected: false}
        ],
        days:[
            {value:'周一',  id:'1',selected: false},
            {value:'周二',id:'2', selected: false},
            {value:'周三', id:'3',selected: false},
            {value:'周四', id:'4',selected: false},
            {value:'周五', id:'5',selected: false},
            {value:'周六', id:'6',selected: false},
            {value:'周日', id:'7',selected: false}
        ],
       config:{config1:'inline',config2:'none',config3:'none'},
       selectedMode: '1',
       timeArray: [
           Array.from({length: 10}, (_, i) => (new Date().getFullYear() + i).toString()),
           Array.from({length: 12}, (_, i) => (i + 1).toString().padStart(2, '0')),
           Array.from({length: 31}, (_, i) => (i + 1).toString().padStart(2, '0'))
       ],
       timeIndex: [0, 0, 0],
       selectedTime: '',
       weeklyFrequencyValue: 0,
       monthlyFrequencyValue: 0,
       frequencyDisplay: '每天',
       weeklyTargetDays: 0,  // 添加本周目标天数
       weeklyCompletedDays: 0  // 添加本周已完成天数
    },

    // 添加计算目标天数的函数
    calculateTargetDays: function() {
        const type = parseInt(this.data.selectedMode);
        let targetDays = 0;

        if (type === 1) {
            // 固定频率，计算选中的天数
            targetDays = this.data.days.filter(day => day.selected).length;
            if (targetDays === 0) targetDays = 7; // 如果没有选择，默认为每天
        } else if (type === 2) {
            // 每周频率
            targetDays = this.data.weeklyFrequencyValue;
        } else if (type === 3) {
            // 每月频率，转换为每周目标
            targetDays = Math.ceil(this.data.monthlyFrequencyValue / 4);
        }

        this.setData({
            weeklyTargetDays: targetDays
        });
    },

    // 添加检查完成状态的函数
    checkCompletionStatus: function() {
        const completedDays = this.data.weeklyCompletedDays;
        const targetDays = this.data.weeklyTargetDays;

        if (completedDays === targetDays) {
            wx.showModal({
                title: '恭喜',
                content: '本轮任务已完成！',
                showCancel: false
            });
        } else if (completedDays > targetDays) {
            wx.showModal({
                title: '太棒了',
                content: '恭喜你超额完成任务！',
                showCancel: false
            });
        }
    },

    // 修改选择频率时的处理
    chooseNum: function(e) {
        var id = e.target.id;
        this.setData({
            selectedMode: id,
            config:{
                config1: id == '1' ? 'inline' : 'none',
                config2: id == '2' ? 'inline' : 'none',
                config3: id == '3' ? 'inline' : 'none'
            }
        });
        this.updateFrequencyDisplay();
        this.calculateTargetDays();
    },

    // 修改自定义频率的处理
    customTime1: function(e) {
        const value = parseInt(e.detail.value) || 0;
        if (value > 7) {
            wx.showModal({
                title: '提示',
                content: '每周打卡天数不能超过7天',
                showCancel: false,
                success: () => {
                    this.setData({
                        weeklyFrequencyValue: 7
                    }, () => {
                        this.updateFrequencyDisplay();
                        this.calculateTargetDays();
                    });
                }
            });
        } else {
            this.setData({
                weeklyFrequencyValue: value
            }, () => {
                this.updateFrequencyDisplay();
                this.calculateTargetDays();
            });
        }
    },

    customTime2: function(e) {
        const value = parseInt(e.detail.value) || 0;
        if (value > 31) {
            wx.showModal({
                title: '提示',
                content: '每月打卡天数不能超过31天',
                showCancel: false,
                success: () => {
                    this.setData({
                        monthlyFrequencyValue: 31
                    }, () => {
                        this.updateFrequencyDisplay();
                        this.calculateTargetDays();
                    });
                }
            });
        } else {
            this.setData({
                monthlyFrequencyValue: value
            }, () => {
                this.updateFrequencyDisplay();
                this.calculateTargetDays();
            });
        }
    },

    // 修改日期选择的处理
    days: function(e) {
        const index = e.currentTarget.dataset.index;
        const days = [...this.data.days];
        days[index].selected = !days[index].selected;
        this.setData({
            days: days
        });
        this.updateFrequencyDisplay();
        this.calculateTargetDays();
    },

    // 在页面加载时初始化目标天数
    onLoad: function (options) {
        // 初始化时间选择器，设置当前日期
        const now = new Date();
        const currentYear = now.getFullYear();
        const currentMonth = now.getMonth() + 1;
        const currentDay = now.getDate();

        // 设置初始选中日期
        this.setData({
            timeIndex: [
                this.data.timeArray[0].indexOf(currentYear.toString()),
                this.data.timeArray[1].indexOf(currentMonth.toString().padStart(2, '0')),
                this.data.timeArray[2].indexOf(currentDay.toString().padStart(2, '0'))
            ]
        });
        if(getApp().globalData.edit){
            const editedHabit = getApp().globalData.My_Habits.find(h => h.habit_id == options.Id);
            if (editedHabit) {
                // 格式化结束时间以便picker显示
                let finishedTime = '';
                if (editedHabit.habit_finishedTime) {
                    finishedTime = editedHabit.habit_finishedTime.split(' ')[0];
                    const [year, month, day] = finishedTime.split('-');
                    this.setData({
                        timeIndex: [
                            this.data.timeArray[0].indexOf(year),
                            this.data.timeArray[1].indexOf(month),
                            this.data.timeArray[2].indexOf(day)
                        ],
                        selectedTime: finishedTime
                    });
                }

                // 处理打卡情景的选中状态
                const habit_times = this.data.habit_times.map(item => ({
                    ...item,
                    selected: editedHabit.punch_in_scenarios && editedHabit.punch_in_scenarios.includes(item.value)
                }));

                // 处理打卡频率的选中状态和值
                let selectedDays = this.data.days.map(day => ({...day, selected: false}));
                let weeklyValue = 0;
                let monthlyValue = 0;

                if (editedHabit.habit_frequency_type === 1) {
                    if (editedHabit.habit_frequency_days) {
                        const freqDays = editedHabit.habit_frequency_days.split(',').map(Number);
                        selectedDays = selectedDays.map((day, index) => ({
                            ...day,
                            selected: freqDays.includes(index + 1)
                        }));
                    }
                } else if (editedHabit.habit_frequency_type === 2) {
                    weeklyValue = editedHabit.habit_frequency_value;
                } else if (editedHabit.habit_frequency_type === 3) {
                    monthlyValue = editedHabit.habit_frequency_value;
                }

                this.setData({
                    habit: {
                        id: editedHabit.habit_id,
                        icon: editedHabit.habit_img ? '../../' + editedHabit.habit_img : '../../icon/new.png',
                        name: editedHabit.habit_name
                    },
                    selectedMode: editedHabit.habit_frequency_type ? editedHabit.habit_frequency_type.toString() : '1',
                    config: {
                        config1: editedHabit.habit_frequency_type === 1 ? 'inline' : 'none',
                        config2: editedHabit.habit_frequency_type === 2 ? 'inline' : 'none',
                        config3: editedHabit.habit_frequency_type === 3 ? 'inline' : 'none'
                    },
                    days: selectedDays,
                    weeklyFrequencyValue: weeklyValue,
                    monthlyFrequencyValue: monthlyValue,
                    habit_times: habit_times
                });
            } else {
                // 如果没找到习惯，重置编辑状态
                getApp().globalData.edit = false;
                wx.showToast({
                    title: '未找到要编辑的习惯',
                    icon: 'none'
                });
                this.setData({
                    habit: {
                        id: 0,
                        icon: '../../icon/new.png',
                        name: '未命名'
                    },
                    selectedMode: '1',
                    config: {config1:'inline',config2:'none',config3:'none'},
                    days: this.data.days.map(day => ({...day, selected: false})),
                    weeklyFrequencyValue: 0,
                    monthlyFrequencyValue: 0,
                    habit_times: this.data.habit_times.map(item => ({...item, selected: false}))
                });
            }
        }
        else{
        if(options.id!=0){
            const app=getApp();
            this.setData({
                habit:{
                id:options.id,
                icon:'../../'+app.globalData.Habits_library[options.id-1].habit_icon,
                name:app.globalData.Habits_library[options.id-1].habit_name}
            });
        }
        else{
            this.setData({
                habit:{
                id:0,
                icon:'../../icon/new.png',
                name:'未命名'}
            });
        }}
        
        // 在设置完所有数据后，计算目标天数
        this.calculateTargetDays();
    },
   name: function(res){
    var that=this;
    that.data.habit.name=res.detail.value;
     that.setData({
       habit:that.data.habit
     });
   },
   
    sub: function() {
        // Common data extraction for both add and edit
        const userId = wx.getStorageSync('userId') || app.globalData.user_id;
        const habitName = this.data.habit.name;

        // 检查习惯名称是否为空
        if (!habitName || habitName.trim() === '') {
            wx.showToast({
                title: '请输入习惯名称',
                icon: 'none'
            });
            return;
        }

        const log_CreateTime = new Date().toISOString().slice(0, 19).replace('T', ' ');

        const selectedScenarios = this.data.habit_times
            .filter(item => item.selected)
            .map(item => item.value)
            .join(',');

        let habit_frequency_type = parseInt(this.data.selectedMode);
        let habit_frequency_value = 0;
        let habit_frequency_days = null;

        if (habit_frequency_type === 1) {
            habit_frequency_days = this.data.days
                .filter(day => day.selected)
                .map(day => day.id)
                .join(',');
        } else if (habit_frequency_type === 2) {
            habit_frequency_value = this.data.weeklyFrequencyValue;
        } else if (habit_frequency_type === 3) {
            habit_frequency_value = this.data.monthlyFrequencyValue;
        }

        if(getApp().globalData.page_type == 1) {
            wx.switchTab({
                url: '../../pages/record/record'
            });
        } else if (getApp().globalData.edit) { // Handle edit existing habit
            const habitId = this.data.habit.id;
            const requestData = {
                habit_id: habitId,
                user_id: userId,
                habit_name: habitName.trim(),
                habit_img: this.data.habit.icon || '',
                habit_finishedTime: this.data.selectedTime ? this.data.selectedTime + ' 23:59:59' : null,
                habit_customTime: this.data.habit.customTime || 0,
                punch_in_scenarios: selectedScenarios || null,
                habit_frequency_type: habit_frequency_type,
                habit_frequency_value: habit_frequency_value,
                habit_frequency_days: habit_frequency_days,
            };

            console.log('Sending update data to backend:', requestData);
            wx.request({
                url: 'http://127.0.0.1:3001/updateUserHabit',
                method: 'POST',
                header: {
                    'content-type': 'application/json'
                },
                data: requestData,
                success: (res) => {
                    console.log('Backend update response:', res.data);
                    if (res.data.success) {
                        wx.showToast({
                            title: '更新成功',
                            icon: 'success'
                        });
                        getApp().globalData.edit = false;
                        const pages = getCurrentPages();
                        const habitsPage = pages.find(page => page.route === 'pages/habits/habits');
                        if (habitsPage) {
                            habitsPage.loadHabits(userId);
                        }
                        const recordPage = pages.find(page => page.route === 'pages/record/record');
                        if (recordPage) {
                            recordPage.loadHabits(userId);
                        }
                        wx.switchTab({
                            url: '../habits/habits',
                        });
                    } else {
                        wx.showToast({
                            title: res.data.message || '更新失败',
                            icon: 'error'
                        });
                    }
                },
                fail: (err) => {
                    console.error('更新习惯失败:', err);
                    wx.showToast({
                        title: '更新失败',
                        icon: 'error'
                    });
                }
            });
        } else { // Handle add new habit
            const requestData = {
                userId: userId,
                habit_name: habitName.trim(),
                habit_img: this.data.habit.icon || '',
                habit_createdTime: log_CreateTime,
                habit_finishedTime: this.data.selectedTime ? this.data.selectedTime + ' 23:59:59' : null,
                habit_customTime: this.data.habit.customTime || 0,
                habit_num: 0,
                isClockedInToday: 0,
                is_finished: 0,
                punch_in_scenarios: selectedScenarios || null,
                habit_frequency_type: habit_frequency_type,
                habit_frequency_value: habit_frequency_value,
                habit_frequency_days: habit_frequency_days
            };
            console.log('Sending add data to backend:', requestData);
            
            wx.request({
                url: 'http://127.0.0.1:3001/addUserHabit',
                method: 'POST',
                header: {
                    'content-type': 'application/json'
                },
                data: requestData,
                success: (res) => {
                    console.log('Backend response:', res.data);
                    if (res.data.success) {
                        wx.showToast({
                            title: '添加成功',
                            icon: 'success'
                        });
                        const pages = getCurrentPages();
                        const habitsPage = pages.find(page => page.route === 'pages/habits/habits');
                        if (habitsPage) {
                            habitsPage.loadHabits(userId);
                        }
                        const recordPage = pages.find(page => page.route === 'pages/record/record');
                        if (recordPage) {
                            recordPage.loadHabits(userId);
                        }
                        wx.switchTab({
                            url: '../habits/habits',
                        });
                    } else {
                        wx.showToast({
                            title: res.data.message || '添加失败',
                            icon: 'error'
                        });
                    }
                },
                fail: (err) => {
                    console.error('添加习惯失败:', err);
                    wx.showToast({
                        title: '添加失败',
                        icon: 'error'
                    });
                }
            });
        }
    },

    bindTimeChange: function(e) {
        const values = e.detail.value;
        const year = parseInt(this.data.timeArray[0][values[0]]);
        const month = parseInt(this.data.timeArray[1][values[1]]);
        const day = parseInt(this.data.timeArray[2][values[2]]);

        const selectedDate = new Date(year, month - 1, day);
        const now = new Date();
        const today = new Date(now.getFullYear(), now.getMonth(), now.getDate()); // Get today's date without time

        if (selectedDate < today) {
            wx.showToast({
                title: '不能选择过去的日期',
                icon: 'none',
                duration: 2000
            });
            // Revert to the previously selected valid date or current date
             const previousTimeIndex = this.data.timeIndex;
             const prevYear = parseInt(this.data.timeArray[0][previousTimeIndex[0]]);
             const prevMonth = parseInt(this.data.timeArray[1][previousTimeIndex[1]]);
             const prevDay = parseInt(this.data.timeArray[2][previousTimeIndex[2]]);
             const prevSelectedTime = `${prevYear}-${prevMonth.toString().padStart(2, '0')}-${prevDay.toString().padStart(2, '0')}`;

            this.setData({
                timeIndex: previousTimeIndex,
                selectedTime: prevSelectedTime
            });
            return;
        }

        const timeString = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
        
        this.setData({
            timeIndex: values,
            selectedTime: timeString
        });
    },

    bindTimeColumnChange: function(e) {
        const column = e.detail.column;
        const value = e.detail.value;
        const timeIndex = this.data.timeIndex;
        timeIndex[column] = value;

        const now = new Date();
        const currentYear = now.getFullYear();
        const currentMonth = now.getMonth() + 1;
        const currentDay = now.getDate();

        // 处理月份天数变化
        if (column === 1) { // 月份改变时
            const year = parseInt(this.data.timeArray[0][timeIndex[0]]);
            const month = parseInt(this.data.timeArray[1][value]); // Use value directly for month index
            const daysInMonth = new Date(year, month + 1, 0).getDate(); // Month is 0-indexed in Date constructor
            const daysArray = Array.from({length: daysInMonth}, (_, i) => (i + 1).toString().padStart(2, '0'));
            
            // 如果当前选中的日期大于新的月份天数，则调整为最后一天
            if (timeIndex[2] >= daysInMonth) {
                timeIndex[2] = daysInMonth - 1;
            }

            this.setData({
                'timeArray[2]': daysArray,
                timeIndex: timeIndex
            });
        }
        // 处理闰年2月天数变化
        else if (column === 0) { // 年份改变时
            const year = parseInt(this.data.timeArray[0][value]); // Use value directly for year index
            const month = parseInt(this.data.timeArray[1][timeIndex[1]]);
             const daysInMonth = new Date(year, month + 1, 0).getDate(); // Month is 0-indexed in Date constructor
            const daysArray = Array.from({length: daysInMonth}, (_, i) => (i + 1).toString().padStart(2, '0'));
            
            // 如果当前选中的日期大于新的月份天数，则调整为最后一天
            if (timeIndex[2] >= daysInMonth) {
                timeIndex[2] = daysInMonth - 1;
            }

            this.setData({
                'timeArray[2]': daysArray,
                timeIndex: timeIndex
            });
        }
        
        // 检查是否选择了过去的日期，如果是，则重置到当前日期
        const selectedYear = parseInt(this.data.timeArray[0][timeIndex[0]]);
        const selectedMonth = parseInt(this.data.timeArray[1][timeIndex[1]]);
        const selectedDay = parseInt(this.data.timeArray[2][timeIndex[2]]);

        const selectedDate = new Date(selectedYear, selectedMonth, selectedDay); // Month is 0-indexed in Date constructor
        const today = new Date(now.getFullYear(), now.getMonth(), now.getDate()); // Get today's date without time
        
        if (selectedDate < today) {
             // 如果选择的是过去的日期，将选择重置为当前日期
            const currentYearIndex = this.data.timeArray[0].indexOf(currentYear.toString());
            const currentMonthIndex = this.data.timeArray[1].indexOf(currentMonth.toString().padStart(2, '0'));
            const currentDayIndex = this.data.timeArray[2].indexOf(currentDay.toString().padStart(2, '0'));

             timeIndex[0] = currentYearIndex;
             timeIndex[1] = currentMonthIndex;
             // Re-calculate days in current month just in case
            const daysInCurrentMonth = new Date(currentYear, currentMonth, 0).getDate();
            const daysArray = Array.from({length: daysInCurrentMonth}, (_, i) => (i + 1).toString().padStart(2, '0'));
            
            timeIndex[2] = currentDayIndex;
            
            this.setData({
                 'timeArray[2]': daysArray,
                 timeIndex: timeIndex
            });

        } else {
             this.setData({
                timeIndex: timeIndex
            });
        }

    },

    // 选择打卡情景
    selectScenario: function(e) {
        const index = e.currentTarget.dataset.index;
        // 将其他选项设为未选中
        const habit_times = this.data.habit_times.map((item, i) => ({
            ...item,
            selected: i === index ? !item.selected : false
        }));
        this.setData({ habit_times });
    },

    updateFrequencyDisplay: function() {
        const type = parseInt(this.data.selectedMode);
        let displayText = '';

        if (type === 1) {
            // 固定频率，显示具体的周几
            const selectedDays = this.data.days
                .filter(day => day.selected)
                .map(day => day.value);
            
            if (selectedDays.length === 0 || selectedDays.length === 7) {
                displayText = '每天';
            } else {
                displayText = selectedDays.join('、');
            }
        } else if (type === 2) {
            // 每周频率
            const value = this.data.weeklyFrequencyValue;
            if (value === 7) {
                displayText = '每天';
            } else if (value > 0) {
                displayText = `每周${value}天`;
            } else {
                displayText = '每周';
            }
        } else if (type === 3) {
            // 每月频率
            const value = this.data.monthlyFrequencyValue;
            if (value === 31) {
                displayText = '每天';
            } else if (value > 0) {
                displayText = `每月${value}天`;
            } else {
                displayText = '每月';
            }
        }

        console.log('Updating frequency display:', {
            type,
            weeklyValue: this.data.weeklyFrequencyValue,
            monthlyValue: this.data.monthlyFrequencyValue,
            displayText
        });

        this.setData({
            frequencyDisplay: displayText
        });
    },

    // 添加打卡处理函数（这个函数需要在打卡时调用）
    handleClockIn: function() {
        const completedDays = this.data.weeklyCompletedDays + 1;
        this.setData({
            weeklyCompletedDays: completedDays
        });
        this.checkCompletionStatus();
    }
});